import time
import os
import re
import errno
import inspect
import datetime
import uuid
import traceback
import threading
import threadpool

from daemon import Daemon
from rpyc_rpc import RpycRpc
from utils import Exp, _dmsg, _dwarn, _derror, \
    etchosts_update, cpu_usage, _exec_shell, _exec_pipe, \
    mutil_exec, _get_value, _human_unreadable, _human_readable, \
    _exec_pipe1, _exec_remote1, _lock_file, _exec_system, _get_remote, \
    _get_backtrace

def __line__ ():
    caller = inspect.stack()[3]
    return caller[1], int (caller[2])

class Log():
    def __init__(self, log_path, foreground=False):
        self.log_path = log_path
        self.foreground = foreground

    def _dmsg(self, level, msg):
        f,l = __line__()
        msg = "%s/%d %s %s:%s %s: %s" %(time.strftime('%Y-%m-%d %H:%M:%S'),
                    time.time(), os.getpid(), f, l, level, msg)
        if self.foreground:
            print msg
        else:
            f = open(self.log_path, 'a')
            f.write(msg + '\n')
            f.close()

    def _dinfo(self, msg):
        self._dmsg("INFO", msg)

    def _dwarn(self, msg):
        self._dmsg("WARNING", msg)

    def _derror(self, msg):
        self._dmsg("ERROR", msg)
